import Alertift
import ProgressHUD
import UIKit

class AccountDeletionViewController: UIViewController {

  // MARK: - UI Elements
  private let titleLabel: UILabel = {
    let label = UILabel()
    label.font = UIFont.boldSystemFont(ofSize: 24)
    label.textAlignment = .left
    label.numberOfLines = 0
    return label
  }()
  var userData: UserData = UserDefaults.baoDan.loadUserDataFromUserDefaults()!

  private let descriptionLabel: UILabel = {
    let label = UILabel()
    label.numberOfLines = 0
    label.textAlignment = .left
    return label
  }()

  private let deleteButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("确认申请", for: .normal)
    button.backgroundColor = .red
    button.tintColor = .white
    button.layer.cornerRadius = 8
    return button
  }()

  // MARK: - View Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    setupUI()
    titleLabel.text =
      "您正在注销\(cryptPhone(userData.phone) ?? userData.userName ?? "")在本客户端的服务功能，请谨慎操作。此操作将永久删除您的账户和所有相关数据。此操作不可撤销，请确认。"
    descriptionLabel.text = """
      1. 爆单键盘客户端将不再为当前号码提供登录、查询、业务办理等相关业务；
      2. 如您想继续使用查询、业务办理等相关服务，请您联系客服进行办理；
      3. 账号删除冷静期为30天，期间不可再登录此账号，若登录则自动取消申请。冷静期后将停止此账号在爆单键盘App的登录、查询、办理等一系列服务。 
      """
    deleteButton.addTarget(self, action: #selector(deleteAccount), for: .touchUpInside)
  }

  private func cryptPhone(_ phone: String?) -> String? {
    guard let phone = phone else {
      return nil
    }

    // 确保电话号码长度至少为11位
    guard phone.count >= 11 else {
      return nil
    }

    // 获取需要替换的范围（第5位到第8位，即索引4到7）
    let start = phone.index(phone.startIndex, offsetBy: 4)
    let end = phone.index(phone.startIndex, offsetBy: 8)
    let range = start..<end

    // 替换为 ****
    let newPhone = phone.replacingCharacters(in: range, with: "****")

    return newPhone
  }

  private func setupUI() {
    // Layout all UI elements
    view.addSubview(titleLabel)
    view.addSubview(descriptionLabel)
    view.addSubview(deleteButton)

    // Setup constraints
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
    deleteButton.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
      titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
      titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
      titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),

      descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 20),
      descriptionLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
      descriptionLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),

      deleteButton.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 40),
      deleteButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
      deleteButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
      deleteButton.heightAnchor.constraint(equalToConstant: 50),
    ])
  }

  // MARK: - Actions

  @objc private func deleteAccount() {
    let alertController = UIAlertController(
      title: "确认删除",
      message: "您确定要删除您的账户和所有数据吗？此操作不可撤销。",
      preferredStyle: .alert)

    alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))

    alertController.addAction(
      UIAlertAction(
        title: "删除", style: .destructive,
        handler: { [weak self] _ in
          self?.performAccountDeletion()
        }))

    present(alertController, animated: true, completion: nil)
  }

  private func performAccountDeletion() {
    ProgressHUD.animate("loading....", interaction: false)
    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
      Alertift.alert(title: "提醒", message: "已完成申请，账号进入冷静期！点击确定将退出登录。")
        .action(.destructive("确定")) { [weak self] in
          guard let self = self else { return }
          ProgressHUD.dismiss()
          self.logoutNetWork()
        }
        .show()
    }
  }

  private func logoutNetWork() {
    // TODO: 实现退出登录逻辑
    HttpClient.shared.post(endpoint: "/logout", body: [:]) {
      (result: Result<String, NetworkError>) in
      DispatchQueue.main.async {

        switch result {
        case .success(_):
          if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate
            as? SceneDelegate
          {
            let window = sceneDelegate.window
            UserDefaults.baodan.removeUserDataFromUserdefaults()

            // 切换根视图控制器
            UIView.transition(
              with: window!, duration: 0.5, options: .transitionCrossDissolve,
              animations: {
                window?.rootViewController = WelcomeViewController()  // 登录成功后，切换到主页面
              })
          }
        case .failure(let error):

          // ❌ 处理错误
          switch error {
          case .serverError(let code):
            ProgressHUD.failed("服务器错误: \(code)")
          case .noData:
            ProgressHUD.failed("未收到服务器响应")
          case .decodingError:
            ProgressHUD.failed("数据解析错误")
          case .invalidURL:
            ProgressHUD.failed("无效的URL")
          case .customError(let message):
            ProgressHUD.failed(message)
          }
        }
      }
    }
  }
}
